package services

import (
	"errors"
	"gitee.com/phpdi/ant-api/entitys"
	"gitee.com/phpdi/ant-api/utils"
	"github.com/astaxie/beego"
	"time"
)

//登录验证服务
type AuthService struct {
	jwt       *jwtService         //jwt认证服务
	loginUser entitys.User // 当前登录用户
	openUrl   []string            //未登录能访问的权限

	loginCachePrefix string        //登录缓存前缀
	tokenLifeTime    time.Duration //token有效时间 单位秒
}

func NewAuth() *AuthService {
	this := &AuthService{
		jwt:              NewJwtService(),
		loginCachePrefix: beego.AppConfig.String("appname") + ":loginCachePrefix:",
		tokenLifeTime:    86400,
		openUrl:[]string{
			"main/login",
		},
	}

	return this
}


// 获取当前登录的用户对象
func (this *AuthService) GetUser() entitys.User {
	return this.loginUser
}

//获取token认证密码
func (this *AuthService) CreateToken() (string,error) {
	customClaims:=entitys.CustomClaims{
		UserId:this.loginUser.Id,
	}

	customClaims.ExpiresAt=time.Now().Add(this.tokenLifeTime*time.Second).Unix()

	return this.jwt.CreateToken(customClaims)
}

// 检查是否登录
func (this *AuthService) IsLogined() bool {
	return this.loginUser.Id >0
}

// 是否为不登录能访问的权限
func (this *AuthService) IsNoAuthPerm(module, action string) bool {
	return utils.InArray(module+"/"+action,this.openUrl)
}

// 用户登录
func (this *AuthService) Login(login entitys.Login) (token string, err error) {

	if this.loginUser, err = UserService.GetUserByName(login.UserName);err!= nil {
		return
	}

	//检查密码
	if this.loginUser.Password!=utils.Md5(login.Password+this.loginUser.Salt) {
		return "",errors.New("密码错误")
	}

	if token ,err= this.CreateToken();err!= nil {
		return
	}

	return
}


//手动设置登录用户
func (this *AuthService) SetUser(userId uint32) (err error) {
	this.loginUser, err = UserService.One(userId)

	return
}

//通过token设置登录用户
func (this *AuthService)SetUserByToken(token string) (err error) {
	var claims *entitys.CustomClaims
	if claims,err=this.jwt.ParseToken(token);err!= nil {
		return
	}

	if this.loginUser,err= UserService.One(claims.UserId);err!=nil{
		return
	}

	return nil
}

